<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">入库记录</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">查询信息</text>
      </view>
      <view class="info-form">
        <!-- <view class="form-item">
          <text class="form-label">查询日期</text>
          <text class="warehouse-display">{{ formData.currentDate }}</text>
        </view> -->
        <view class="form-item">
          <text class="form-label">仓库</text>
          <picker
            mode="selector"
            :range="targetWarehouseOptions"
            range-key="text"
            :value="currentWarehouseIndex"
            @change="handleWarehouseChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{
                currentWarehouse ? currentWarehouse.warehouseName : "请选择仓库"
              }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- C. 查询/选择区 -->
    <view class="search-section">
      <view class="section-header">
        <text class="section-title">查询条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="
              handleTimeChange('today');
              handleSearch();
            "
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="
              handleTimeChange('week');
              handleSearch();
            "
          >
            近7天
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'month' }"
            @tap="
              handleTimeChange('month');
              handleSearch();
            "
          >
            近1个月
          </button>
        </view>
      </view>
      <!-- D. 列表 -->
      <view class="section-header">
        <text class="section-title">汇总统计</text>
        <view class="statistics-info">
          <text class="stat-item">总重: {{ totalWeight }} KG</text>
          <text class="stat-item">总件数: {{ totalCount }}</text>
        </view>
      </view>
      <view
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 8rpx;
        "
      >
        <!-- 增加一行小字：每次最多查询100条数据，更多请滑动底部加载更多 -->
        <text
          class="section-subtitle"
          style="
            font-size: 20rpx;
            color: #999;
            text-align: center;
            width: 100%;
            display: block;
          "
          >每次最多查询100条数据，更多请滑动底部加载</text
        >
      </view>
      <scroll-view class="table-scroll" scroll-y @scrolltolower="onReachBottom">
        <view class="table-row header">
          <!-- <text class="header-cell">单据编号</text> -->
          <text class="header-cell">入库日期</text>
          <view class="table-cell">钢种</view>
          <view class="table-cell">规格</view>
          <view class="table-cell">净重(KG)</view>
          <view class="table-cell">箱号</view>
          <view class="table-cell">轴号</view>
          <view class="table-cell">批号</view>
        </view>
        <view
          v-for="(item, index) in detailTableData"
          :key="index"
          class="table-row"
        >
          <!-- <text class="table-cell">{{ item.inNo }}</text> -->
          <text class="table-cell">{{
            item.inDate ? dateHelperApi.formatDate(item.inDate) : "-"
          }}</text>
          <view class="table-cell">{{ item.steelGradeName || "-" }}</view>
          <view class="table-cell">{{ item.prodSpec }}</view>
          <view class="table-cell">{{
            (item.weightOfNet || 0).toFixed(3)
          }}</view>
          <view class="table-cell">{{ item.boxCode || "-" }}</view>
          <view class="table-cell">{{ item.axisCode || "-" }}</view>
          <view class="table-cell">{{ item.batchNo || "-" }}</view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { ProdStockInApi } from "@/api/warehouse/prodstockin";
import { warehouseApi } from "@/api/warehouse/warehouse";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
export default {
  name: "StockIn",
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        warehouseCode: "",
        warehouseName: "",
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },
      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
      },
      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 表格数据
      detailTableData: [],
      detailLoading: false,
      // 加载状态
      loading: false,
      // 分页与刷新
      refreshing: false,
      pageNum: 1,
      hasMore: true,
      // 仓库选项列表
      targetWarehouseOptions: [],
      // 当前仓库索引
      currentWarehouseIndex: -1,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 总重量计算
    totalWeight() {
      return this.detailTableData
        .reduce((total, item) => {
          return total + (parseFloat(item.weightOfNet) || 0);
        }, 0)
        .toFixed(3);
    },
    // 总件数计算（细丝按boxCode，其他按axisCode）
    totalCount() {
      return this.detailTableData.filter((item) => {
        // 细丝：有boxCode无axisCode
        if (item.boxCode && !item.axisCode) {
          return true;
        }
        // 其他：有axisCode
        if (item.axisCode) {
          return true;
        }
        return false;
      }).length;
    },
  },
  onLoad() {
    this.loadCurrentWarehouse();
    this.loadWarehouseOptions(); // 加载仓库选项
    // 页面加载时初始化时间范围并加载数据
    this.handleTimeChange("today");
    this.$nextTick(() => {
      this.handleSearch();
    });
  },
  methods: {
    /* 加载当前仓库 */
    loadCurrentWarehouse() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.wmName) {
        this.currentWarehouse = {
          warehouseCode: userConfig.wmCode || "DEFAULT",
          warehouseName: userConfig.wmName,
        };
        this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
        this.formData.warehouseName = this.currentWarehouse.warehouseName;
      }
    },

    /* 加载仓库选项 */
    async loadWarehouseOptions() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          dictType: "wm_name_prod",
        };
        const response = await warehouseApi.getWarehouseList(params);
        if (response.code === 0) {
          // 将数据转换为下拉选项格式，根据API返回的字段名称
          this.targetWarehouseOptions = (response.data.list || []).map(
            (item) => ({
              value: item.value,
              text: item.label,
              warehouseName: item.label, // 用于显示
            })
          );
          console.log("目标仓库数据加载成功:", this.targetWarehouseOptions);

          // 如果当前有仓库，设置对应的索引
          if (this.currentWarehouse && this.currentWarehouse.warehouseName) {
            const index = this.targetWarehouseOptions.findIndex(
              (option) =>
                option.warehouseName === this.currentWarehouse.warehouseName
            );
            if (index !== -1) {
              this.currentWarehouseIndex = index;
            }
          }
        }
      } catch (error) {
        console.error("加载仓库选项失败:", error);
      }
    },

    /* 处理仓库选择变化 */
    handleWarehouseChange(e) {
      const index = e.detail.value;
      this.currentWarehouseIndex = index;
      const selectedWarehouse = this.targetWarehouseOptions[index];
      if (selectedWarehouse) {
        this.currentWarehouse = {
          warehouseCode: selectedWarehouse.value,
          warehouseName: selectedWarehouse.warehouseName,
        };
        this.formData.warehouseCode = selectedWarehouse.value;
        this.formData.warehouseName = selectedWarehouse.warehouseName;

        // 重新搜索数据
        this.handleSearch();
      }
    },

    /* 下拉刷新 = 重置 */
    onPullDownRefresh() {
      // 重置所有相关状态
      this.detailTableData = [];
      this.hasMore = true;
      this.pageNum = 1;
      this.refreshing = true;

      // 停止刷新状态
      setTimeout(() => {
        this.refreshing = false;
      }, 500);

      // 重新初始化时间范围并搜索 - 使用重置模式
      this.handleTimeChange(this.timeFilter);
      this.$nextTick(() => {
        this.handleSearch(false); // 明确传递false，确保是重置而不是加载更多
      });
    },
    /* 触底加载 */
    onReachBottom() {
      if (this.loading) return;
      this.pageNum++;
      this.handleSearch(true);
    },
    /* 搜索主表 */
    async handleSearch(loadMore = false) {
      if (!loadMore) {
        this.detailTableData = [];
        this.hasMore = true;
        this.pageNum = 1;
      }
      this.loading = true;

      // 构建查询参数
      const params = {
        pageNo: this.pageNum, // 注意：有些后端接口使用pageNo而不是pageNum
        pageSize: 100,
        materialName: this.searchForm.materialName || "",
        materialCode: this.searchForm.materialCode || "",
        warehouseName: this.currentWarehouse.warehouseName || "",
      };
      // 只有在时间范围有效时才添加时间参数
      if (this.timeRange.startTime && this.timeRange.endTime) {
        params.inDate = [this.timeRange.startTime, this.timeRange.endTime];
      }
      console.log("=== 发送请求参数 ===");
      console.log("当前页码 pageNum:", this.pageNum);
      console.log("是否为加载更多 loadMore:", loadMore);
      console.log("完整请求参数:", params);
      console.log("后端接口URL: /wm/prod-stock-in/page");

      try {
        const response = await ProdStockInApi.getProdStockInPage(params);
        console.log("response:", response.data);
        if (response.code === 0) {
          // 数据去重处理 - 使用复合键唯一标识一条记录
          const newData = response.data.list.filter((newItem) => {
            return !this.detailTableData.some((existingItem) => {
              // 使用入库日期+钢种+规格+净重+箱号+轴号+批号作为唯一标识
              const newItemKey = `${newItem.inDate}_${newItem.steelGradeName}_${newItem.prodSpec}_${newItem.weightOfNet}_${newItem.boxCode}_${newItem.axisCode}_${newItem.batchNo}`;
              const existingItemKey = `${existingItem.inDate}_${existingItem.steelGradeName}_${existingItem.prodSpec}_${existingItem.weightOfNet}_${existingItem.boxCode}_${existingItem.axisCode}_${existingItem.batchNo}`;
              return newItemKey === existingItemKey;
            });
          });

          if (loadMore && newData.length === 0) {
            // 加载更多但没有新数据，说明已经到底了
            this.hasMore = false;
            uni.showToast({
              title: "没有更多数据了",
              icon: "none",
            });
          } else {
            this.detailTableData.push(...newData);
            this.hasMore = response.data.list.length === 10;
          }
        } else {
          uni.showToast({
            title: response.message || "加载数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      setTimeout(() => {
        this.loading = false;
      }, 600);
    },
    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.statistics-info {
  display: flex;
  gap: 30rpx;
}

.stat-item {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.warehouse-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f8f8;
  padding: 16rpx 24rpx;
  border-radius: 8rpx;
  min-width: 200rpx;
}

.picker-arrow {
  color: #999;
  font-size: 24rpx;
  margin-left: 16rpx;
}
</style>
